package hms.FrontDeskModule;


import java.awt.event.ActionEvent;

import hms.generic.AbstractGlobalView;
import hms.master.*;
import hms.permissions.Permission;
import hms.reservations.ReservationView;
import hms.rooms.Room;
import hms.ReservationsModule.Guest;
import hms.database.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.GregorianCalendar;
import java.util.Vector;

import javax.swing.JPanel;

import java.awt.GridBagLayout;

import javax.swing.JTable;
import javax.swing.JOptionPane;
import javax.swing.JList;
import java.awt.GridBagConstraints;
import javax.swing.table.DefaultTableModel;
import java.awt.Insets;

import javax.swing.ListSelectionModel;

import java.awt.Component;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import java.awt.FlowLayout;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import java.awt.BorderLayout;
import javax.swing.border.TitledBorder;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Font;
import java.awt.event.ActionListener;


public class RoomServicesView extends AbstractGlobalView  {
	
	private JPanel contentPane;
	private JTextField display;
	private JPanel panel_1;
	private JPanel panel_2;
	private JPanel panel_3;
	private JPanel panel_4;
	private JScrollPane scrollPane_1;
	private JScrollPane scrollPane_2;
	private JScrollPane scrollPane_3;
	private JButton roomSearchButton;
	private JButton orderButton;
	private JList roomList;
	private JTextArea infoTextArea;
	private Vector<String> roomLabelVector = new Vector<String>();
	private Vector<String> roomServiceVector=new Vector<String>();
	private JList serviceList;
	private int roomID;
	private JButton addServiceButton;
	private JLabel lblYourSelection;

	/**
	 * Create the frame.
	 */
	public RoomServicesView() {
		initComponent();
		super.update(contentPane);
		super.display();
	}
	
	private void initComponent(){
		 contentPane = new JPanel();
		 contentPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Room Service", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		 
		 panel_1 = new JPanel();
		 panel_1.setBorder(new TitledBorder(null, "Room", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		 
		 panel_2 = new JPanel();
		 panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Room Information", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		 
		 panel_3 = new JPanel();
		 panel_3.setBorder(new TitledBorder(null, "Available Service", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		 
		 panel_4 = new JPanel();
		 
		 display = new JTextField();
		 display.setEditable(false);
		 display.setColumns(10);
		 
		 lblYourSelection = new JLabel("Your Selection:");
		 GroupLayout gl_contentPane = new GroupLayout(contentPane);
		 gl_contentPane.setHorizontalGroup(
		 	gl_contentPane.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_contentPane.createSequentialGroup()
		 			.addContainerGap()
		 			.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 						.addComponent(panel_4, 0, 0, Short.MAX_VALUE)
		 						.addGroup(gl_contentPane.createSequentialGroup()
		 							.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)
		 							.addGap(46)
		 							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 								.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE)
		 								.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 337, Short.MAX_VALUE))))
		 					.addGap(48))
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addComponent(lblYourSelection)
		 					.addGap(16)
		 					.addComponent(display, GroupLayout.PREFERRED_SIZE, 226, GroupLayout.PREFERRED_SIZE)
		 					.addContainerGap(290, Short.MAX_VALUE))))
		 );
		 gl_contentPane.setVerticalGroup(
		 	gl_contentPane.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_contentPane.createSequentialGroup()
		 			.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addGap(14)
		 					.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
		 					.addPreferredGap(ComponentPlacement.UNRELATED)
		 					.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
		 					.addGap(8))
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addContainerGap()
		 					.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)))
		 			.addGap(18)
		 			.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
		 			.addPreferredGap(ComponentPlacement.RELATED)
		 			.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
		 				.addComponent(display, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
		 				.addComponent(lblYourSelection))
		 			.addGap(8))
		 );
		 panel_3.setLayout(new BoxLayout(panel_3, BoxLayout.X_AXIS));
		 
		 scrollPane_3 = new JScrollPane();
		 panel_3.add(scrollPane_3);
		 
		 serviceList = new JList();
		 serviceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		 serviceList.setFont(new Font("MS Reference Sans Serif", Font.BOLD, 14));
		 scrollPane_3.setViewportView(serviceList);
		 
		 roomServiceVector=disService(); //Fetch room service data from the DB and display it using this list
		 serviceList.setListData(roomServiceVector);//Initialize the list with the data from the DB
		 
		 //default select the first item 
		 serviceList.setSelectedIndex(0);
		 
		 roomSearchButton = new JButton("Room Search");
		 roomSearchButton.setToolTipText("Please select a room in the list");
		 
		 /* Object rItem=roomList.getSelectedValue();
		 //System.out.println(rItem);
		 if(rItem==null)
			 roomSearchButton.setEnabled(false);
		 else
			 roomSearchButton.setEnabled(true);
		 */
		 
		 roomSearchButton.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		roomSearch();
		 	}
		 });
		 roomSearchButton.setActionCommand("roomSearchButton");
		 
		 orderButton = new JButton("Order");
		 orderButton.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		roomServiceOrder();
		 	}
		 });
		 
		 addServiceButton = new JButton("Add Service");
		 addServiceButton.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		addRoomService();
		 	}
		 });
		 GroupLayout gl_panel_4 = new GroupLayout(panel_4);
		 gl_panel_4.setHorizontalGroup(
		 	gl_panel_4.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_panel_4.createSequentialGroup()
		 			.addGap(67)
		 			.addComponent(roomSearchButton)
		 			.addPreferredGap(ComponentPlacement.RELATED, 174, Short.MAX_VALUE)
		 			.addComponent(orderButton)
		 			.addGap(18)
		 			.addComponent(addServiceButton)
		 			.addGap(24))
		 );
		 gl_panel_4.setVerticalGroup(
		 	gl_panel_4.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_panel_4.createSequentialGroup()
		 			.addContainerGap()
		 			.addGroup(gl_panel_4.createParallelGroup(Alignment.BASELINE)
		 				.addComponent(roomSearchButton)
		 				.addComponent(orderButton)
		 				.addComponent(addServiceButton))
		 			.addContainerGap(12, Short.MAX_VALUE))
		 );
		 panel_4.setLayout(gl_panel_4);
		 panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.X_AXIS));
		 
		 scrollPane_2 = new JScrollPane();
		 panel_2.add(scrollPane_2);
		 
		 infoTextArea = new JTextArea();
		 infoTextArea.setFont(new Font("MS Reference Sans Serif", Font.BOLD, 14));
		 infoTextArea.setEditable(false);
		 scrollPane_2.setViewportView(infoTextArea);
		 panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS));
		 
		 scrollPane_1 = new JScrollPane();
		 panel_1.add(scrollPane_1);
		 
		 roomList = new JList();
		 roomList.setFont(new Font("MS Reference Sans Serif", Font.BOLD, 14));
		 roomList.setModel(new AbstractListModel() {
		 	String[] values = new String[] {"RM-1001", "Room1"};
		 	public int getSize() {
		 		return values.length;
		 	}
		 	public Object getElementAt(int index) {
		 		return values[index];
		 	}
		 });
		 
		 roomLabelVector=disRoomLabel(); //Fetch room label data from the DB and display it using this list
		 roomList.setListData(roomLabelVector);//Initialize the list with the data from the DB
		 //default select the first item as default
		 roomList.setSelectedIndex(0);
		 scrollPane_1.setViewportView(roomList);
		 contentPane.setLayout(gl_contentPane);
		 
		 if(!checkPermission(Permission.OFFER_ADDITIONAL_GUEST_SERVICES)) {
			 orderButton.setEnabled(false);
			 addServiceButton.setEnabled(false);
		 }
	    } 

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equalsIgnoreCase("guestSearchButton")) {
			
		}
		if (e.getActionCommand().equalsIgnoreCase("roomSearchButton")) {
			roomSearch();
		}
		if (e.getActionCommand().equalsIgnoreCase("payMethodButton")) {
            
		}	
	}
	
	public void roomSearch(){
		String roomLabel=" ";
		String gFirstName = " ";
		String gLastName = " ";
		
		Object room=" ";
		room=roomList.getSelectedValue();
		roomLabel=room.toString();
		//System.out.println(roomLabel);
		display.setText("You Select Room: "+roomLabel);
		
		DAO localDAO = MasterController.getDatabaseObject();
        
        ResultSet rs1 = localDAO.getResult("Select* from ROOM where ROOMLABEL='"+roomLabel+"';");
        try {
			while(rs1.next()){
				roomID=rs1.getInt("ROOMID");
				//System.out.println("ROOM ID is: "+roomID);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
        
        ReservationView rv = new ReservationView();
		rv.fillForRoomOnDate(new Room(roomID), new GregorianCalendar());
		Guest guest = new Guest(rv.get(0).getPayingCustomerID());
		gFirstName = guest.getFirstName();
		gLastName = guest.getLastName();
        
        if(gFirstName==" "||gLastName==" "){
        	infoTextArea.setText("");
        	infoTextArea.append("ROOM LABEL:  "+roomLabel+"\n");
        	infoTextArea.append("ROOM STATUS:  "+"EMPTY"+"\n");
        }
        else{
        	infoTextArea.setText("");
        	infoTextArea.append("ROOM LABEL:  "+roomLabel+"\n");
        	infoTextArea.append("GUEST NAME:  "+gFirstName+" "+gLastName+"\n");
        }
	}
	
	public Vector<String> disRoomLabel(){
		Vector<String> roomLabel = new Vector<String>();
		
		// TODO Ben date this
		
		DAO localDAO = MasterController.getDatabaseObject();
		ResultSet rs = localDAO.getResult("Select ROOMLABEL from ROOM where ROOMID in (select ROOMID from ROOM_RESERVATION);");
		try {
			
			while(rs.next()){
				roomLabel.add(rs.getObject("ROOMLABEL").toString());
				
			}
			//for(int i=0;i<roomLabel.size();i++)
				//System.out.println(roomLabel.get(i));
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
        return roomLabel;	
	}
	
	public Vector<String> disService(){
		Vector<String> serviceVector = new Vector<String>();
		
		DAO localDAO = MasterController.getDatabaseObject();
		ResultSet rs = localDAO.getResult("Select* from ROOM_SERVICE");
		try {
			
			while(rs.next()){
				String serviceDes=rs.getObject("DESCRIPTION").toString();
				double servicePrice=rs.getDouble("PRICE");
				String service = String.format("%s:                    $%4.2f", serviceDes,servicePrice);
				//String service=serviceDes+":    "+servicePrice;
				serviceVector.add(service);		
				
			}			
		} catch (SQLException e) {
			e.printStackTrace();
		}
        return serviceVector;	
	}
	
	public int roomServiceOrder(){
		Object o=serviceList.getSelectedValue();
        String service="";
        service=o.toString();
        //System.out.println(service);
        String s[]=service.split(":");
        String sDescription=s[0];
        double sPrice=Double.parseDouble(s[1].replace("$", ""));
        int RSID = 0; //Room_Service_ID
        int reservationID=-1;
        //System.out.println(sDescription);
        //System.out.println(sPrice);
        
     // Query to find Room_Service_ID
        DAO localDAO = MasterController.getDatabaseObject();
		ResultSet rs = localDAO.getResult("Select* from ROOM_SERVICE where DESCRIPTION='"+sDescription+"';");
		try {
			
			while(rs.next()){
				RSID=rs.getInt("ROOM_SERVICE_ID");			
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//System.out.println("The Room Service ID is:" + RSID);
		
		//Query to find Reservation_ID via ROOMID which get from the roomSearch()
		//String query= "select* from ROOM,ROOM_RESERVATION where ROOM_RESERVATION.ROOMID="+roomID+";";
		ReservationView rv = new ReservationView();
		rv.fillForRoomOnDate(new Room(roomID), new GregorianCalendar());
		reservationID = rv.get(0).getUniqueIdentifier();
		//System.out.println("RESERVATION ID is:"+reservationID);
        //System.out.println("Room ID is:"+roomID);
		
		//check whether the order had been placed or not
		String checkSQL="select DESCRIPTION from ROOM_SERVICE,ROOM_SERVICE_RESERVATION where "+
						"ROOM_SERVICE.ROOM_SERVICE_ID=ROOM_SERVICE_RESERVATION.ROOM_SERVICE_ID and ROOMID="+roomID+";";
				
		ResultSet rs2 = localDAO.getResult(checkSQL);
		try {
					
			while(rs2.next()){
				String des=rs2.getString("DESCRIPTION");
				if(sDescription.equalsIgnoreCase(des)){
					JOptionPane.showMessageDialog(contentPane,"This order has been placed!","Error",JOptionPane.ERROR_MESSAGE);
					return 0;
				}
			}
							
		} catch (SQLException e) {
			    e.printStackTrace();
			  }
		
		
		   // Order a room service and Add it to the DB 
		String insertSQL = "INSERT INTO ROOM_SERVICE_RESERVATION(ROOM_SERVICE_ID, ROOMID, RESERVATION_ID)" +
        		"VALUES("+RSID+","+roomID+","+reservationID+");";
		//invalid reservation id
		if(reservationID==-1){
			JOptionPane.showMessageDialog(contentPane,"Please search a room first!","Error",JOptionPane.ERROR_MESSAGE);
			return 0;
		}
			
        if(localDAO.updateCommand(insertSQL))
        	JOptionPane.showMessageDialog(contentPane,"Order Confirmed!");
        else
        	JOptionPane.showMessageDialog(contentPane,"Order fails or a same order has been placed","Error",JOptionPane.ERROR_MESSAGE);
        return 1;
	}
	
	public void addRoomService(){
		String serviceDescription="";
		double price=0.0;
		userInputBox addService=new userInputBox();
		serviceDescription=addService.getDescription();
		price=addService.getPrice();
		//System.out.println("description: " + serviceDescription);
        //System.out.println("price: " + price);
        
        String insertSQL="INSERT INTO ROOM_SERVICE(DESCRIPTION,PRICE)VALUES" +
        		"('"+serviceDescription+"',"+price+");";
        DAO localDAO = MasterController.getDatabaseObject();
        // Add a user specified service into the DB
        if(!serviceDescription.equalsIgnoreCase("")&&price!=0.0){
        	if(localDAO.updateCommand(insertSQL))
            	JOptionPane.showMessageDialog(contentPane,"You Successfully Add a Room Service!");
            else
            	JOptionPane.showMessageDialog(contentPane,"Error Occurs!","Error",JOptionPane.ERROR_MESSAGE);
        }
        //reload the serviceList where display all the available services
        Vector<String> s= disService();
        serviceList.setListData(s);
	}
	
	class userInputBox{
		public JTextField descriptionField;
		  private JTextField priceField;
		  private JPanel myPanel;
		  private JLabel label1;
		  private JLabel label2;
		  private String serviceDescription="";
		  private double price=0.0;

		  userInputBox(){
	          descriptionField = new JTextField(5);
		      priceField = new JTextField(5);
		      label1 = new JLabel();
		      label2 = new JLabel();
		      myPanel = new JPanel();
		      myPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		      JLabel label = new JLabel("Description:");
		      myPanel.add(label);
		      myPanel.add(descriptionField);
		      JLabel label_1 = new JLabel("Price:");
		      myPanel.add(label_1);
		      myPanel.add(priceField);

		      int result = JOptionPane.showConfirmDialog(null, myPanel,
		               "Please Enter Service Description and Price", JOptionPane.OK_CANCEL_OPTION);
		      if (result == JOptionPane.OK_OPTION) {
		    	 serviceDescription=descriptionField.getText();
			     price=Double.parseDouble(priceField.getText());
		    	 //System.out.println("description: " + descriptionField.getText());
		         //System.out.println("price: " + priceField.getText());
		      }

		  }
		  
		  public String getDescription(){
				 return serviceDescription;
		  }
			 
		  public double getPrice(){
				 return price;
		  }
	}
	
}
